import datetime
import json

import pytz
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from iotutils.iothub import debug_on, debug_off, new_client
from thickcharts.models import Mdata, Device
from utils.utils import query_to_list, devices_filter


def hello(request):
    return HttpResponse("hello test")

# 获取壁厚和温度的数据
def get_mdatas(request):
    if request.method == 'GET':
        probe = request.GET.get('probe')
        mdatas = []
        mdatas_query = Mdata.objects.filter(probe=probe)
        for mdata_query in mdatas_query:
            mdatas.append(mdata_query.to_dict())
        res = {
            'data': {'mdatas': mdatas},
            'meta': {'status': 200, 'message': "获取厚度和温度数据成功"}
        }
    else:
        res = {
            'data': {},
            'meta': {'status': 402, 'message': "获取厚度和温度数据失败，请发起get请求"}
        }
    return JsonResponse(res)

# 根据条件查询设备列表
def search_probes(request):
    if request.method == 'GET':
        query = request.GET.get('query')
        pagenum = int(request.GET.get('pagenum'))
        pagesize = int(request.GET.get('pagesize'))
        devices_query = devices_filter(query)
        total = devices_query.count()
        paginator = Paginator(devices_query, pagesize)
        num_pages = paginator.num_pages
        if pagenum > num_pages:
            pagenum = num_pages
        page_devices_query = paginator.page(pagenum)
        page_devices_list = query_to_list(page_devices_query)
        res = {
            'data': {'total': total, 'devices': page_devices_list, 'pagenum': pagenum},
            'meta': {'status': 200, 'message': '探头列表查询成功'}
        }
    else:
        res = {
            'data': {'devices': []},
            'meta': {'status': 402, 'message': '设备列表查询失败，请发起get请求'}
        }
    return JsonResponse(res)

# 获取腐蚀数据的视图函数
def corrosion_data(request):
    if request.method == 'GET':
        query = request.GET.get('deviceQuery')
        startDate = request.GET.get('startDate')
        endDate = request.GET.get('endDate')
        if startDate and endDate:
            startDate = datetime.datetime.fromtimestamp(int(startDate))
            endDate = datetime.datetime.fromtimestamp(int(endDate))
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': '请选择腐蚀计算的开始和结束日期'}
            }
            return JsonResponse(res)
        pagenum = int(request.GET.get('pagenum'))
        pagesize = int(request.GET.get('pagesize'))
        devices_query = devices_filter(query)
        total = devices_query.count()
        paginator = Paginator(devices_query, pagesize)
        num_pages = paginator.num_pages
        if pagenum > num_pages:
            pagenum = num_pages
        page_devices_query = paginator.page(pagenum)
        page_devices_list = query_to_list(page_devices_query)
        for device in page_devices_list:
            periodMdata = Mdata.objects.filter(probe=device['probe']).filter(add_time__lte=endDate, add_time__gte=startDate).order_by('add_time')
            if periodMdata:
                thick_change = abs(periodMdata.first().thickness - periodMdata.last().thickness)
                device['thick_change'] = round(thick_change, 2)
            else:
                device['thick_change'] = 0
        res = {
            'data': {'total': total, 'devices': page_devices_list, 'pagenum': pagenum},
            'meta': {'status': 200, 'message': '获取腐蚀数据列表成功'}
        }
        return JsonResponse(res)

# 获取单个探头的腐蚀曲线的数据
def corrosion_chart(request):
    if request.method == 'GET':
        deviceId = request.GET.get('deviceId')
        offdays = int(request.GET.get('offdays'))
        device = Device.objects.filter(pk=deviceId)
        if not device.exists():
            res = {
                'data': {},
                'meta': {'status': 201, 'message': '查询探头信息失败'}
            }
            return JsonResponse(res)
        probe = device.first().probe
        device_datas = Mdata.objects.filter(probe=probe).order_by('add_time')
        m_dates = []
        thick_changes = []
        for device_data in device_datas:
            front_mdata = device_datas.filter(add_time__date=device_data.add_time-datetime.timedelta(days=offdays))
            if front_mdata.exists():
                front_mdata = front_mdata.first()
                m_dates.append(device_data.add_time.date())
                thick_change = round(abs(device_data.thickness - front_mdata.thickness), 2)
                thick_changes.append(thick_change)
        res = {
            'data': {'m_dates': m_dates, 'thick_changes': thick_changes, 'offdays': offdays},
            'meta': {'status': 200, 'message': '获取腐蚀速率曲线数据成功'}
        }
        return JsonResponse(res)

# 根据id数据获取对应探头的波形数据
def get_wave(request):
    if request.method == 'GET':
        device_id = request.GET.get('deviceId')
        device = Device.objects.get(pk=device_id)
        start = device.start
        width = device.width
        scan_range = device.scan_range
        gain = device.gain
        if device.wave:
            wave = json.loads(device.wave)
            length = len(wave)
            x_data = [i for i in range(length)]
        else:
            wave = []
            x_data = [i for i in range(10)]
        res = {
            "meta": {"status": 200, "message": "获取波形数据成功"},
            "data": {"wave": wave, "x_data": x_data, "start": start, "width": width, "scan_range": scan_range, "gain": gain}
        }
        return JsonResponse(res)

# 是否开启波形数据的debug模式
def debug(request):
    state = request.GET.get("state")
    deviceId = request.GET.get("deviceId")
    device = Device.objects.filter(pk=deviceId).first()
    if state == 'on':
    #     开启debug 模式
        try:
            debug_on(device)
            res = {
                "meta": {"status": 200, "message": "开启debug模式成功"},
                "data": {}
            }
        except:
            res = {
                "meta": {"status": 404, "message": "开启debug模式失败，请联系管理员"},
                "data": {}
            }
        return JsonResponse(res)
    else:
    #     关闭debug模式
        try:
            debug_off(device)
            res = {
                "meta": {"status": 200, "message": "关闭debug模式成功"}
            }
        except:
            res = {
                "meta": {"status": 400, "message": "关闭debug模式失败"}
            }
        return JsonResponse(res)

# 为给定的device设置壁厚解析需要的闸门起始，闸门宽度，增益等信息。
def set_params(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        device_id = data.get("deviceId")
        start = data.get("start")
        width = data.get("width")
        scan_range = data.get("scanRange")
        gain = data.get("gain")
        devices = Device.objects.filter(pk=device_id)
        if devices.count():
            device = devices.first()
            client_id = device.client_id
            probe = device.probe
            device.start = start
            device.width = width
            device.scan_range = scan_range
            device.gain = gain
            device.save()
            client = new_client()
            payload = {
                # state:2 表示给下位机下发设置参数
                "client_id": client_id,
                "probe": probe,
                "flag": 2,
                "scan_range": int(scan_range),
                "gain": int(gain),
                "strobe_start": int(start),
                "strobe_range": int(width),
            }
            down_topic = 'thick/down/' + client_id
            client.publish(down_topic, json.dumps(payload))
            client.disconnect()
            res = {
                "meta": {"status": 200, "message": "下发设置参数成功"},
                "data": {}
            }
        else:
            res = {
                "meta": {"status": 404, "message": "下发参数出现错误，未找到对应的探头数据"}
            }
        return JsonResponse(res)

